package tool

import (
	"fmt"
	"math/rand"
	"os"
	"reflect"
	"strings"
	"time"
)

func PathExist(path string) bool {
	stat, err := os.Stat(path)
	if err == nil {
		if stat.IsDir() {
			return true
		}
	}
	return false
}

func FileExist(file string) bool {
	stat, err := os.Stat(file)
	if err == nil {
		if !stat.IsDir() {
			return true
		}
	}
	return false
}

func GetPath(params ...interface{}) string {
	format := ""
	for i := range params {
		kind := reflect.TypeOf(params[i]).Kind()
		if kind == reflect.String {
			format += "%s/"
		} else if kind == reflect.Int || kind == reflect.Int32 ||
			kind == reflect.Int8 || kind == reflect.Int64 || kind == reflect.Int16 {
			format += "%d/"
		} else {
			continue
		}
	}
	return fmt.Sprintf(format, params...)
}

func GetPathWithBase(base string, params ...interface{}) string {
	if strings.HasSuffix(base, "/") {
		return base + GetPath(params...)
	} else {
		return base + "/" + GetPath(params...)
	}
}

func GetPathOrCreate(base string, params ...interface{}) (string, error) {
	path := GetPathWithBase(base, params...)
	if !PathExist(path) {
		err := os.MkdirAll(path, 644)
		if err != nil {
			return "", err
		}
	}
	return path, nil
}

func Mkdir(base string, names []string) error {
	for i := 0; i < len(names); i++ {
		err := os.Mkdir(GetPathWithBase(base, names[i]), 644)
		if err != nil {
			for j := i - 1; j >= 0; j-- {
				err := os.Remove(GetPathWithBase(base, names[i]))
				if err != nil {
					return err
				}
			}
			return err
		}
	}
	return nil
}

const (
	chars = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789"
)

func init() {
	rand.Seed(time.Now().Unix())
}

func GetUniqueName(size int, length int) []string {
	names := make([]string, size)
	for i := 0; i < size; i++ {
		for j := 0; j < length; j++ {
			index := rand.Intn(len(chars))
			names[i] += fmt.Sprintf("%c", chars[index])
		}
	}
	return names
}
